<?php
class Admin_LoginController extends Zendvn_Controller_Action{
	
	public function init(){
		
		
	}
	
	
	
	public function indexAction(){
		
		$auth= Zend_Auth::getInstance();
		$info= $auth->getIdentity();
		//$name= new Zend_Session_Namespace('name');
		//$name->username= $info->username;
		
	}
	
	//tao ham chuyen huong dang nhap
	
	 public function preDispatch(){
	$auth= Zend_Auth::getInstance();
	if ($auth->hasIdentity()){
		$log= new Zend_Session_Namespace('check');
	if (!$log->check){
		$this->_redirect('/admin/login/login');
	}
	}
	}
	public function loginAction(){
		$params = array('host'=>'localhost','username'=>'root','password' =>'dragon','dbname'=>'test2');
		$db = new Zend_Db_Adapter_Pdo_Mysql($params);
		$auth = Zend_Auth::getInstance();
		$authAdater = new Zend_Auth_Adapter_DbTable($db);
		$authAdater->setTableName('userdemo')->setIdentityColumn('username')->setCredentialColumn('pass');
		if ($this->_request->isPost()){
			//ket noi csdl
			//$db= Zend_Registry::get('connectDB');
			//khoi tao Zend_Auth
			
			//$auth= Zend_Auth::getInstance();
			
			//tao bang va cot de so sanh
			//$authAdater= new Zend_Auth_Adapter_DbTable($db);
			//$authAdater->setTableName('login')
				//->setIdentityColumn('username')
				//->setCredentialColumn('password');
			//lay du lieu tu form
			$uname= $this->getRequest()->getParam('username');
			$pass= $this->getRequest()-> getParam('password');
			
			//so sanh 
			
			$authAdater->setIdentity($uname);
			$authAdater->setCredential(md5($pass));
		
			//neu log =1 moi dc login
			$select= $authAdater->getDbSelect('log');
			$select ->where('log= 1');
			
			//lay ket qua truy van
			$result= $auth->authenticate($authAdater);
			$flag= false;
			if($result->isValid()){
				
				//lay du lieu khi dang nhap thanh cong
				$data= $authAdater->getResultRowObject(null, 'password');
				
				//luu du lieu vao session
				$auth->getStorage()->write($data);
				$flag= true;
				$render = "ban da dang nhap thanh cong";
			}
			$session= new Zend_Session_Namespace('check');
			$session-> check= $flag;
			
			if ($flag){
				$this->_redirect('/admin/login/index');
			}
			echo $render;
		}
	}
	
	//logout
	public function logoutAction(){
		$auth= Zend_Auth::getInstance();
		$auth->clearIdentity();
		$session= new Zend_Session_Namespace('check');
		$session->check= false;
	}
}